import Vue from "vue";
import Vuex from "vuex";
//引入持久化插件
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    goods: [], //添加到购物车中商品页
  },
  mutations: {
    //添加的mutation
    ADD_CART(state, payload) {
      state.goods.push(payload);
    },
    //第二次以上添加商品时，只需要修改商品数量
    UPDATE_CART(state, payload) {
      state.goods = payload;
    },
  },
  actions: {
    ADD_CART_AC(context, item) {
      var newArr = [...this.state.goods];
      let index = newArr.findIndex((val) => val.item_id === item.item_id);
      if (index === -1) {
        context.commit("ADD_CART", item);
      } else {
        newArr[index].num++;
        context.commit("UPDATE_CART", newArr);
      }
    },
  },
  modules: {},
});
